package com.chen.sample1.web.config;

import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

/**
 * @desc 本地缓存配置文件
 * @Author Chentian
 * @date 2021/9/1
 */
@Configuration
@EnableCaching
public class LocalCacheConfig {
    /** 最后一次写入后经过固定时间过期 */
    public static final byte CAFFEINE_CACHE_EXPIRE_TIME = 10;
    /** 缓存的最大条数 */
    public static final int CAFFEINE_CACHE_MAX_NUM = 10000;

    @Bean
    public CacheManager cacheManager() {
        CaffeineCacheManager cacheManager = new CaffeineCacheManager();
        //Caffeine配置
        Caffeine<Object, Object> caffeine = Caffeine.newBuilder()
                //最后一次写入后经过固定时间过期
                .expireAfterWrite(CAFFEINE_CACHE_EXPIRE_TIME, TimeUnit.MINUTES)
                //缓存的最大条数
                .maximumSize(CAFFEINE_CACHE_MAX_NUM);
        cacheManager.setCaffeine(caffeine);
        return cacheManager;
    }
}
